<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="description" content="">
  <meta name="keywords" content="">
  
    <link rel="icon" href="/avatar.jpg">
  
    
  <title>Nuxt+Jest 构建页面级的快照测试 | 科学君的不科学博客</title>
  <link rel="stylesheet" href="/style.css">
  <link rel="stylesheet" href="/lib/jquery.fancybox.min.css">
  <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <script type="text/javascript" src="https://tajs.qq.com/stats?sId=65546304" charset="UTF-8"></script>
  <script>
  (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      }
      else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>
</head>

<body>
  <header>
  <div class="header-container">
    <a class='logo' href="/">
      <span>科学君的不科学博客</span>
    </a>
    <ul class="right-header">
      
        <li class="nav-item">
          
            <a href="/" class="item-link">首页</a>
          
        </li>
      
        <li class="nav-item">
          
            <a href="/about" class="item-link">关于</a>
          
        </li>
      
        <li class="nav-item">
          
            <a href="/archives" class="item-link">归档</a>
          
        </li>
      
        <li class="nav-item">
          
            <a href="/tags" class="item-link">标签</a>
          
        </li>
      
        <li class="nav-item">
          
            <a href="/atom.xml" class="item-link">FEED 订阅</a>
          
        </li>
      
    </ul>
  </div>
</header>

  <main id='post'>
  <div class="content">
    <article>
      <section class="content markdown-body">
        <h1>Nuxt+Jest 构建页面级的快照测试</h1>
        <div class='post-meta'>
          <i class="fa fa-calendar" aria-hidden="true"></i>
          <time>2018年03月25日</time>
          
          | <i class="fa fa-folder-open-o" aria-hidden="true"></i> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/blog/">blog</a>
  </div>



          
          
          |
          
          <i class="fa fa-tags" aria-hidden="true"></i>
          
          
  <a href="/tags/#前端" class='tag'>前端</a>

  <a href="/tags/#vue" class='tag'>vue</a>

  <a href="/tags/#jest" class='tag'>jest</a>


          
        </div>
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>我最近的一个网站用到了 Vue 的 nuxtjs 框架，这个框架的<a href="https://nuxtjs.org/guide/development-tools" target="_blank" rel="noopener">示例</a> 中用的是 ava。很不巧，WebStorm 不支持 ava，所以我打算用 jest 来进行快照测试。在折腾的过程中，我发现了一种神奇的方法，可以 将 nuxt 的构建过程同测试框架完美配合起来，这样在进行快照测试的时候不需要配置 jest 的 babel， 只需要让 jest 来比较生成出的 html 即可。不过缺点就是只能进行页面级的快照测试，没法单独测试 某个组件的快照了。</p>
<h1 id="生成-html"><a href="#生成-html" class="headerlink" title="生成 html"></a>生成 html</h1><p>我们可以用 nuxt 的构建工具直接生成 html，这样就可以使用 nuxt 的构建设置了。 首先我们在项目的根目录下建立 <code>/__test__/pages</code> 文件夹，当然你也可以不用这个路径，只是注意改一下 之后代码里的路径就好。然后在这个路径里建立一个 <code>pages_snapshot.test.js</code> ，写入：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> &#123;Nuxt, Builder&#125; = <span class="built_in">require</span>(<span class="string">'nuxt'</span>)</span><br><span class="line"><span class="keyword">const</span> &#123;resolve&#125; = <span class="built_in">require</span>(<span class="string">'path'</span>)</span><br><span class="line"><span class="keyword">const</span> cheerio = <span class="built_in">require</span>(<span class="string">'cheerio'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// We keep a reference to Nuxt so we can close</span></span><br><span class="line"><span class="comment">// the server at the end of the test</span></span><br><span class="line"><span class="keyword">let</span> nuxt = <span class="literal">null</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Init Nuxt.js</span></span><br><span class="line">beforeAll(<span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> rootDir = resolve(__dirname, <span class="string">'../..'</span>)</span><br><span class="line">  <span class="keyword">const</span> config = <span class="built_in">require</span>(resolve(rootDir, <span class="string">'nuxt.config.js'</span>))</span><br><span class="line">  config.rootDir = rootDir <span class="comment">// project folder</span></span><br><span class="line">  config.dev = <span class="literal">false</span> <span class="comment">// production build</span></span><br><span class="line">  nuxt = <span class="keyword">new</span> Nuxt(config)</span><br><span class="line">  <span class="keyword">await</span> <span class="keyword">new</span> Builder(nuxt).build()</span><br><span class="line">&#125;, <span class="number">1200000</span>) <span class="comment">// 用两分钟的时间启动 nuxt</span></span><br></pre></td></tr></table></figure>
<p>这段代码是直接启动 nuxt 的构建系统来编译前端文件，这段代码我是从 <a href="https://nuxtjs.org/guide/development-tools" target="_blank" rel="noopener">https://nuxtjs.org/guide/development-tools</a> 里面拿来的，但是去掉了最后的 <code>listen</code> 。注意这里必须要用 <code>require</code> 而不是 es6 的 <code>import</code> 来 引入组件，因为这个文件还是在 node 里运行的，且没有经过 babel 编译。</p>
<p>然后就可以用下面的代码来生成 html 并测试快照了：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'page /'</span>, <span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> context = &#123;&#125;</span><br><span class="line">  <span class="keyword">const</span> &#123;html&#125; = <span class="keyword">await</span> nuxt.renderRoute(path, context)</span><br><span class="line"></span><br><span class="line">  expect(html).toMatchSnapshot()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>要运行这个测试用例，只需要 <code>npm i -D jest</code> 然后在 <code>package.json</code> 里面加上一个 script 即可：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"scripts"</span>: &#123;</span><br><span class="line">    <span class="attr">"test"</span>: <span class="string">"jest __test__/"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后运行 <code>npm test</code> 即可得到一堆错误。接下来我来讲解一下解决办法。</p>
<h1 id="timer-unref-is-not-a-function"><a href="#timer-unref-is-not-a-function" class="headerlink" title="timer.unref is not a function"></a><code>timer.unref is not a function</code></h1><p>我在 <a href="https://github.com/facebook/jest/issues/1909" target="_blank" rel="noopener">https://github.com/facebook/jest/issues/1909</a> 找到了它的解决办法，修改一下 package.json， 增加一个配置项即可：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"jest"</span>: &#123;</span><br><span class="line">    <span class="attr">"testEnvironment"</span>: <span class="string">"node"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="生成的快照糊到了一起"><a href="#生成的快照糊到了一起" class="headerlink" title="生成的快照糊到了一起"></a>生成的快照糊到了一起</h1><p>由于 <code>render</code> 得到的 html 是 production 状态的，经过了压缩。而 jest 的 toMatchSnapshot 是按行比较的。因此我们需要先把得到的 html 美化一下，再生成快照，我们可以直接用 jest 的 <code>jest-serializer-html</code> 来做到。先安装： <code>npm i -D jest-serializer-html</code> ，然后在 package 的 jest 字段里面加一个 snapshotSerializers，配置项就变成了这样：</p>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"jest"</span>: &#123;</span><br><span class="line">    <span class="attr">"snapshotSerializers"</span>: [</span><br><span class="line">      <span class="string">"jest-serializer-html"</span></span><br><span class="line">    ],</span><br><span class="line">    <span class="attr">"testEnvironment"</span>: <span class="string">"node"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样 jest 就会用这个工具来自动格式化生成的 html 了。</p>
<h1 id="每次修改-js-快照都会改变"><a href="#每次修改-js-快照都会改变" class="headerlink" title="每次修改 js 快照都会改变"></a>每次修改 js 快照都会改变</h1><p>因为快照的 html 中还包括 webpack 打包出来的 css 和 js 文件，每次修改这些文件的时候 hash 值 都会被改变，然后快照里的相应文件名就改变了。由于我们只需要网页 dom 的快照，不需要这些东西， 我们可以直接把相应的 tag 删掉。我是用 cheerio 做到的，如果你喜欢的话，也可以用其他的工具。</p>
<p>首先安装它 <code>npm i -D cheerio</code> 。</p>
<p>然后修改一下刚刚的测试文件，在获取到 html 的时候进行一些奇妙的操作：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'page /'</span>, <span class="keyword">async</span> () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> context = &#123;&#125;</span><br><span class="line">  <span class="keyword">const</span> &#123;html&#125; = <span class="keyword">await</span> nuxt.renderRoute(path, context)</span><br><span class="line">  <span class="keyword">const</span> $ = cheerio.load(html)</span><br><span class="line"></span><br><span class="line">  $(<span class="string">'link[href^="/_nuxt/"]'</span>).remove()</span><br><span class="line">  $(<span class="string">'script[src^="/_nuxt/"]'</span>).remove()</span><br><span class="line"></span><br><span class="line">  expect($.html()).toMatchSnapshot()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>我们移除了所有包含以 <code>/_nuxt/</code> 打头的文件的script和link。</p>
<h1 id="快照中会出现-data-v-xxx-或者-data-vue-ssr-id-之类的奇怪东西"><a href="#快照中会出现-data-v-xxx-或者-data-vue-ssr-id-之类的奇怪东西" class="headerlink" title="快照中会出现 data-v-xxx 或者 data-vue-ssr-id 之类的奇怪东西"></a>快照中会出现 <code>data-v-xxx</code> 或者 <code>data-vue-ssr-id</code> 之类的奇怪东西</h1><p>这两个是 vue 在生成页面的时候生成的，在不同的系统中结果也不一样，而且在修改单文件组件的 <code>style scoped</code> 时也会改变。我们当然也不需要这些东西。</p>
<p>再魔改一下刚刚的代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">test(<span class="string">'page /'</span>, () =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> context = &#123;&#125;</span><br><span class="line">  <span class="keyword">const</span> &#123;html&#125; = <span class="keyword">await</span> nuxt.renderRoute(path, context)</span><br><span class="line">  <span class="keyword">const</span> $ = cheerio.load(html)</span><br><span class="line"></span><br><span class="line">  $(<span class="string">'link[href^="/_nuxt/"]'</span>).remove()</span><br><span class="line">  $(<span class="string">'script[src^="/_nuxt/"]'</span>).remove()</span><br><span class="line">  <span class="comment">// 移除 data-v- 开头的属性和 data-vue-ssr-id 属性</span></span><br><span class="line">  $(<span class="string">'*'</span>).each(<span class="function">(<span class="params">i, el</span>) =&gt;</span> &#123;</span><br><span class="line">    $(el).removeAttr(<span class="string">'data-vue-ssr-id'</span>)</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> key <span class="keyword">in</span> $(el).attr()) &#123;</span><br><span class="line">      <span class="keyword">if</span> (key.startsWith(<span class="string">'data-v-'</span>)) &#123;</span><br><span class="line">        $(el).removeAttr(key)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;)</span><br><span class="line"></span><br><span class="line">  expect($.html()).toMatchSnapshot()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>这样我们的测试就已经差不多能用了。</p>
<p>整个的修改过程可以在 <a href="https://github.com/Liu233w/acm-statistics/compare/df3a685bb307f76193ce88f61bda49497bedf383...ba09a04e9ad2e478f63cde8578ae5594ddd2656d" target="_blank" rel="noopener">https://github.com/Liu233w/acm-statistics/compare/df3a685bb307f76193ce88f61bda49497bedf383...ba09a04e9ad2e478f63cde8578ae5594ddd2656d</a> 看到，欢迎大家捧场。</p>

      </section>
      <div class="license">
        <a href="http://creativecommons.org/licenses/by-sa/3.0/" rel="license" target="_blank">
          <img src="http://i.creativecommons.org/l/by-sa/3.0/88x31.png" style="border-width:0"
               alt="Creative Commons License" class="center">
        </a>
      </div>
      <p>
        本作品采用
        <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank">
          署名-相同方式共享 4.0 国际
        </a>
        进行许可。欢迎转载、使用、重新发布，但务必保留文章署名
        “不科学的科学君” (Liu233w) 与博客链接：
        <a href="https://liu233w.github.io">https://liu233w.github.io</a>
        ，基于本文修改后的作品务必以相同的许可发布。如有任何疑问，请
        <a href="mailto:wwwlsmcom@outlook.com" target="_blank">与我联系</a>
        。
      </p>
    </article>
    
    <!-- disqus 评论框 start -->
    <div class="comment">
      <div id="disqus_thread" class="disqus-thread">
        <i>加载评论框需要翻墙</i>
      </div>
    </div>
    <!-- disqus 评论框 end -->
    
    
    <!-- livere 评论框 start -->
    <div class="comment">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTE5NS8xMTczMA=="></div>
    </div>
    <!-- livere 评论框 end -->
    
  </div>
  <aside>
    
    <div class="toc-container">
      <h1>目录</h1>
      <div class="content">
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#前言"><span class="toc-number">1.</span> <span class="toc-text">前言</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#生成-html"><span class="toc-number">2.</span> <span class="toc-text">生成 html</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#timer-unref-is-not-a-function"><span class="toc-number">3.</span> <span class="toc-text">timer.unref is not a function</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#生成的快照糊到了一起"><span class="toc-number">4.</span> <span class="toc-text">生成的快照糊到了一起</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#每次修改-js-快照都会改变"><span class="toc-number">5.</span> <span class="toc-text">每次修改 js 快照都会改变</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#快照中会出现-data-v-xxx-或者-data-vue-ssr-id-之类的奇怪东西"><span class="toc-number">6.</span> <span class="toc-text">快照中会出现 data-v-xxx 或者 data-vue-ssr-id 之类的奇怪东西</span></a></li></ol>
      </div>
    </div>
    
  </aside>
</main>

<!-- disqus 公共JS代码 -->
<script type="text/javascript">
  /* * * CONFIGURATION VARIABLES * * */
  var disqus_shortname = "liu233w";
  var disqus_identifier = "https://liu233w.github.io/2018/03/25/nuxt-jest-snapshot/";
  var disqus_url = "https://liu233w.github.io/2018/03/25/nuxt-jest-snapshot/";

  isAgent(getDisqus)

  // determine user agent in China
  function isAgent(cb) {
    var url = '//graph.facebook.com/feed?callback=h';
    var xhr = new XMLHttpRequest();
    var called = false;
    xhr.open('GET', url);
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        called = true;
        cb(true);
      }
    };
    xhr.send();
    // timeout 1s, this facebook API is very fast.
    setTimeout(function () {
      if (!called) {
        xhr.abort();
        cb(false)
      }
    }, 1000);
  }

  function getDisqus(isAgent) {
    var dsq = document.createElement('script');
    dsq.type = 'text/javascript';
    dsq.async = true
    dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq)
  }
</script>
<!-- disqus 公共JS代码 end -->


<script type="text/javascript">
  (function (d, s) {
    var j, e = d.getElementsByTagName(s)[0];

    if (typeof LivereTower === 'function') {
      return;
    }

    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;

    e.parentNode.insertBefore(j, e);
  })(document, 'script');
</script>


  <footer>
  <div class="copyright">
    <div>
      &copy; 2019 | Powered by <a href="https://hexo.io" target="_blank">Hexo</a>&nbsp
    </div>
    <div>
      Theme by <a href="https://github.com/lewis-geek/hexo-theme-Aath" target="_blank">Aath</a>
    </div>
  </div>
</footer>


<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script src="/lib/in-view.min.js"></script>
<script src="/lib/lodash.min.js"></script>
<script>
  var isDown = true
  var oldY = 0
  inView.offset(50)

  document.body.addEventListener('touchstart', function(){});
  
  window.addEventListener('scroll', _.throttle(e => {
    var currentY = window.scrollY
    if((oldY - currentY) < 0) {
      isDown = true
    } else {
      isDown = false
    }
    oldY = currentY
  }, 250))

  $("article img").each(function() {
      var strA = "<a data-fancybox='gallery' href='" + this.src + "'></a>";
      $(this).wrapAll(strA);
  });

  $('.toc-link').each(function() {
      var href = $(this).attr("href");
      
      inView(href).on('exit', () => {
        if (isDown) {
          handleActive(href)
        }
      })

      inView(href).on('enter', () => {
        if (!isDown) {
          handleActive(href)
        }
      })

      this.onclick = function(e) {
        var pos = $(href).offset().top - 10;
        $("html,body").animate({scrollTop: pos}, 300);
        setTimeout(() => {
          handleActive(href)
        }, 350)
        return false
      }
  })

  function handleActive(href) {
    document.querySelectorAll('.toc-link').forEach(elm => {
      elm.classList.remove('active')
    })
    document.querySelector(".toc [href='"+ href +"']").classList.add('active')
  }
</script>
<script src="/lib/jquery.fancybox.min.js"></script>

<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

</body>
</html>
